package com.home.security.browser.auth.service;

import com.home.security.browser.auth.entity.SysMenu;
import com.home.security.browser.auth.mapper.AuthUserMapper;
import com.home.common.model.CurrentUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Description:
 * Created by 王大宸 on 2020-10-07 16:25
 * Created with IntelliJ IDEA.
 */
@Service
public class AuthUserService {
    private static final Logger logger = LoggerFactory.getLogger(AuthUserService.class);
    @Autowired
    private AuthUserMapper authUserMapper;

    /***
     * 功能说明：获取用户菜单
     *
     * @author 王大宸
     * @date 2020/10/7 16:29
     * @param appCode 应用code
     * @param user    用户信息
     * @return java.util.List<com.home.security.browser.auth.entity.SysMenu>
     */
    public List<SysMenu> getUserMenu(String appCode, CurrentUser user) {
        if ("admin".equals(user.getUsername())) {
            return getMenuAll(appCode);
        } else {
            return getChildrenMenu(appCode, user.getId());
        }
    }

    /***
     * 功能说明：用户获取菜单
     *
     * @author 王大宸
     * @date 2020/10/7 16:30
     * @param pid     上级菜单id
     * @param userId  用户id
     * @return java.util.List<com.home.security.browser.auth.entity.SysMenu>
     */
    private List<SysMenu> getChildrenMenu(String pid, String userId) {
        List<SysMenu> menus = authUserMapper.getMenuByUser(pid, userId);
        for (SysMenu sysMenu : menus) {
            List<SysMenu> children = getChildrenMenu(sysMenu.getId(), userId);
            if (0 == children.size()) {
                continue;
            }
            sysMenu.setChildren(children);
        }
        return menus;
    }

    /***
     * 功能说明：管理员获取所有菜单
     *
     * @author 王大宸
     * @date 2020/10/7 16:30
     * @param pid  上级菜单id
     * @return java.util.List<com.home.security.browser.auth.entity.SysMenu>
     */
    private List<SysMenu> getMenuAll(String pid) {
        List<SysMenu> menus = authUserMapper.getMenuAll(pid);
        for (SysMenu sysMenu : menus) {
            List<SysMenu> children = getMenuAll(sysMenu.getId());
            if (0 == children.size()) {
                continue;
            }
            sysMenu.setChildren(children);
        }
        return menus;
    }

}
